import { createMemoryHistory, createRouter } from 'vue-router';

// 导入组件
import Login from '../view/login/index.vue';
import Dashboard from '../view/adshboard/index.vue';
import Layout from '../view/test/home.vue';
import Admin from '../view/auth/admin/index.vue';
import Group from '../view/auth/group/index.vue';
import funcitionOder from '../view/function/order/index.vue';
import functionStaff from '../view/function/staff/index.vue';

const routes = [
  {
    path: '/',
    redirect: '/login', // 默认重定向到登录页面
  },
  {
    path: '/login',
    component: Login,
  },
  {
    path: '/dashboard',
    component: Layout,
    name: "main",
    children: [
      {
        path: '',
        meta: {
          id: '1',
          name: '控制台',
          icon: 'House',
          path: '/dashboard',
          describe: '用于展示当前系统中统计的数据、统计报表及重要的实时数据'
        },
        component: Dashboard
      },
      {
        path: 'auth',
        meta: { id: '2', name: '人工智能', icon: 'Grid' },
        children: [
          {
            path: 'admin',
            meta: {
              id: '1',
              name: '通义千问',
              icon: 'Avatar',
              path: '/dashboard/auth/admin',
              describe: '管理员可以进行编辑，权限修改过后需要登出才会生效'
            },
            component: Admin
          },
          {
            path: 'group',
            meta: {
              id: '2',
              name: 'DeepSeek',
              icon: 'Menu',
              path: '/dashboard/auth/group',
              describe: '管理员可以进行编辑，权限修改过后需要登出才会生效'
            },
            component: Group
          }
        ]
      },
      {
        path: 'function',
        meta: { id: '3', name: '图片分析', icon: 'Platform' },
        children: [
          {
            path: 'order',
            meta: {
              id: '1',
              name: '实时监控',
              icon: 'PieChart',
              path: '/dashboard/function/order',
              describe: '管理员可以进行编辑，权限修改过后需要登出才会生效'
            },
            component: funcitionOder
          },
          {
            path: 'staff',
            meta: {
              id: '2',
              name: '监控预警',
              icon: 'FullScreen',
              path: '/dashboard/function/staff',
              describe: '管理员可以进行编辑，权限修改过后需要登出才会生效'
            },
            component: functionStaff
          }
        ]
      }
    ]
  }
];

const router = createRouter({
  history: createMemoryHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = () => {
    // 检查用户是否已登录，例如：检查本地存储中的 token
    const token = localStorage.getItem('token');
    return token !== null;
  };

  if (to.path === '/login') {
    // 如果目标路径是登录页面，直接放行
    next();
  } else {
    if (isAuthenticated()) {
      // 如果已登录，继续导航到目标路径
      next();
    } else {
      // 如果未登录，重定向到登录页面
      next('/login');
    }
  }
});

export default router;